import 'package:OASys/api/MatterApi.dart';
import 'package:OASys/components/FormComponents.dart';
import 'package:OASys/components/scaffoldItem.dart';
import 'package:OASys/entity/MatterVo.dart';
import 'package:flutter/material.dart';

class MatterEditPage extends StatelessWidget {
  final Map arguments;

  MatterEditPage({Key key, this.arguments});
  @override
  Widget build(BuildContext context) {
    return ScaffoldItem(
        '事项信息',
        MatterEdit(
          matterId: arguments['info'] == null ? -1 : arguments['info']['id'],
          isEdit: arguments['isEdit'],
        ));
  }
}

class MatterEdit extends StatefulWidget {
  final int matterId;
  final bool isEdit;

  MatterEdit({Key key, this.matterId, this.isEdit});

  @override
  _MatterEditState createState() => _MatterEditState();
}

class _MatterEditState extends State<MatterEdit> {
  GlobalKey<FormState> formKey = GlobalKey<FormState>();
  MatterVo matterVo;
  MatterVo info;
  DateTime deadlineDay;
  TimeOfDay deadlineTime;
  bool enabled;

  @override
  void initState() {
    super.initState();
    enabled = widget.isEdit;
    if (widget.matterId == -1) {
      setState(() {
        info = new MatterVo();
        matterVo = new MatterVo();
      });
    } else {
      getInfo(widget.matterId);
    }
  }

  void getInfo(int id) {
    MatterApi().info(id, success: (res) {
      setState(() {
        matterVo = res;
        info = res;
        deadlineDay = DateTime.parse(info.deadline);
        deadlineTime = TimeOfDay.fromDateTime(DateTime.parse(info.deadline));
      });
    }, error: (err) {
      print(err.code);
      showFailMessage(context);
    });
  }

  //保存操作
  void save() {
    String deadline =
        bulidDayStr(deadlineDay) + " " + bulidTimeStr(deadlineTime);
    var form = formKey.currentState;
    if (form.validate()) {
      form.save();
      setState(() {
        info.deadline = deadline;
        print(info.toJson().toString());
        doSave(info);
      });
    }
  }

  // 发起保存请求
  void doSave(MatterVo info) {
    print('doSave');
    MatterApi().save(
      info,
      success: (res) {
        Navigator.of(context).pop(true);
      },
      error: (err) {
        print(err.code);
        showFailMessage(context);
      },
    );
  }

  // 重置表单
  void reset() {
    var form = formKey.currentState;
    form.reset();
    setState(() {
      info = MatterVo.fromJson(matterVo.toJson());
      deadlineDay = DateTime.parse(info.deadline);
      deadlineTime = TimeOfDay.fromDateTime(DateTime.parse(info.deadline));
    });
  }

  // 构建时间字符串 用于显示
  String bulidTimeStr(TimeOfDay time) {
    String hour =
        time.hour < 10 ? "0" + time.hour.toString() : time.hour.toString();
    String minute = time.minute < 10
        ? "0" + time.minute.toString()
        : time.minute.toString();
    return hour + ":" + minute + ":00";
  }

  // 构建日期字符串 用于显示
  String bulidDayStr(DateTime dateTime) {
    return dateTime.toString().substring(0, 10);
  }

  @override
  Widget build(BuildContext context) {
    if (info == null || matterVo == null) {
      return Container(
        child: Text('加载中'),
      );
    } else {
      return SingleChildScrollView(
        child: Container(
          width: 500,
          margin: EdgeInsets.all(10),
          child: Card(
            child: Container(
              margin: EdgeInsets.all(10),
              child: Form(
                key: formKey,
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('事项名称：'),
                        FormInput(
                          enabled: enabled,
                          initValue: matterVo.name,
                          hintText: "请输入事项名称",
                          validator: (content) {
                            if (content.length > 12) {
                              return "事项名称过长";
                            } else if (content.length <= 0) {
                              return "事项名称过短";
                            }
                          },
                          onSave: (value) {
                            info.name = value;
                          },
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('事项截止日期：'),
                        Container(
                          width: 200,
                          height: 50,
                          alignment: Alignment.centerLeft,
                          child: FlatButton(
                            minWidth: 200,
                            onPressed: () async {
                              if (!enabled) {
                                return;
                              }
                              if (info.status != 0 && info.status != null) {
                                return;
                              }
                              DateTime result = await showDatePicker(
                                context: context,
                                initialDate: deadlineDay == null
                                    ? DateTime.now()
                                    : deadlineDay,
                                firstDate: DateTime(DateTime.now().year),
                                lastDate: DateTime(2035),
                                helpText: "选择截止日期",
                                cancelText: "取消",
                                confirmText: "保存",
                              );
                              if (result != null) {
                                setState(() {
                                  deadlineDay = result;
                                });
                              }
                            },
                            child: Container(
                              alignment: Alignment.centerLeft,
                              child: Text(
                                deadlineDay == null
                                    ? "请选择截止日期"
                                    : deadlineDay.toString().substring(0, 10),
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 16,
                                  letterSpacing: 1,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('事项截止时间：'),
                        Container(
                          width: 200,
                          height: 50,
                          alignment: Alignment.centerLeft,
                          child: FlatButton(
                            minWidth: 200,
                            onPressed: () async {
                              if (!enabled) {
                                return;
                              }
                              if (info.status != 0 && info.status != null) {
                                return;
                              }
                              var result = await showTimePicker(
                                context: context,
                                initialTime: TimeOfDay.now(),
                                builder: (BuildContext context, Widget child) {
                                  return MediaQuery(
                                    data: MediaQuery.of(context)
                                        .copyWith(alwaysUse24HourFormat: true),
                                    child: child,
                                  );
                                },
                                helpText: "选择截止时间",
                                cancelText: "取消",
                                confirmText: "保存",
                              );
                              if (result != null) {
                                setState(() {
                                  deadlineTime = result;
                                });
                              }
                            },
                            child: Container(
                              alignment: Alignment.centerLeft,
                              child: Text(
                                deadlineTime == null
                                    ? "请选择截止时间"
                                    : bulidTimeStr(deadlineTime),
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 16,
                                  letterSpacing: 1,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('事项内容：'),
                        FormText(
                          enabled: enabled,
                          initValue: matterVo.content,
                          hintText: "请输入事项内容：",
                          validator: (content) {
                            if (content.length > 300) {
                              return "事项内容过长";
                            } else if (content.length <= 0) {
                              return "事项内容过短";
                            }
                          },
                          onSave: (value) {
                            info.content = value;
                          },
                        ),
                      ],
                    ),
                    Visibility(
                      visible: enabled,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          RaisedButton(
                            color: Color.fromRGBO(33, 150, 243, 1),
                            onPressed: save,
                            child: Text(
                              "保 存",
                              style: TextStyle(color: Colors.white),
                            ),
                          ),
                          RaisedButton(
                            color: Color.fromRGBO(103, 194, 58, 1),
                            onPressed: reset,
                            child: Text(
                              "重 置",
                              style: TextStyle(color: Colors.white),
                            ),
                          )
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      );
    }
  }
}
